<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/27
 * Time: 16:20
 */

namespace Home\Controller;


class ChatwithController extends CommonController
{
    /*
     * id绑定接口
     */
    public function bind()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        $user_id = $get['user_id'];///用户id
        $client_id = $get['client_id'];//服务器返回id

        $gateway = new \Home\Service\Gateway();
        //$gateway = new \Org\Util\Gateway();
        $gateway->bindUid($client_id, $user_id);////绑定id
        //$isOnline=$gateway::isUidOnline($user_id);////绑定id

//        $data["type"] = "bind";
//        $data["time"] = time();
//        $data["result"] = "绑定成功";
//        $data["user_id"] = $user_id;
//        $data["code"] = "1001";
        //$data["yanhao"]=$isOnline;

        $data1["type"] = "bind";
        $data1["time"] = time();
        $data1["result"] = "绑定成功";
        $data1["user_id"] = $user_id;
        $data1["code"] = "1001";
        $data4 = json_encode($data1, JSON_UNESCAPED_UNICODE);

        $gateway->sendToUid($user_id, $data4);//像对方发送消息


        //  }//"shop_identifier"=>$get["shop_identifier"]

        // }
        if ($gateway->isUidOnline($user_id) == 1) {
            $chat_record_copy = M('chat_record_copy', Null, 'DB2')->where(["receive_id" => $user_id])->select();
            if ($chat_record_copy) {
                foreach ($chat_record_copy as $kay => $value) {
                    $data6[$kay]["user_id"] = $value["user_id"];///发送人id
                    $data6[$kay]["user_name"] = $value["user_name"];//发送人姓名
                    $data6[$kay]["receive_id"] = $value["receive_id"];//接收人id
                    $data6[$kay]["receive_name"] = $value["receive_name"];//接收人姓名
                    $data6[$kay]["message"] = $value["message"];//消息内容
                    $data6[$kay]["send_time"] = $value["send_time"];//发送时间
                    $data6[$kay]["type"] = $value["type"];//1文字表情，2图片，3语音
                    $data6[$kay]["voic_time"] = $value["voic_time"];//语音时长
//                if(empty($mark)){//信用查
//                    $key="3b8810ed7cca6c75f782b371" ;
//                    $secret="8978f95a5d0ab168604f3787";
//                }else{//DME
//                    $key="79e5e1d58d2b79d0c26e57cc" ;
//                    $secret="dcf8054db178401ccb01d48f";
//                }
//                $app_key = '3b8810ed7cca6c75f782b371'; // appkey
//                $master_secret = '8978f95a5d0ab168604f3787'; // master_secret
//                $client = new \Home\Service\JPush\Client($app_key, $master_secret);
//                $pusher = $client->push();
//                $pusher->setPlatform(array('ios', 'android'));//选择平台
//                $pusher->options(['apns_production' => false]);///开发环境
//                $pusher->addAlias(trim($user_id));///单独推送
//                $pusher->setNotificationAlert($value["user_name"] . '对你说"' . $value["message"] . '"');///推送消息
//                try {
//                    $pusher->send();///开始推送
//                } catch (\JPush\Exceptions\JPushException $e) {
//                    // try something else here
//                    print $e;
//
                }
                //M('chat_record',Null,'DB2')->addAll($data6);json_encode($data6, JSON_UNESCAPED_UNICODE)
                $gateway->sendToUid($user_id, json_encode($data6)); //像对方发送消息
                M('chat_record_copy', Null, 'DB2')->where(["receive_id" => $user_id])->delete();
            }
        }
//        $this->message_api('1213',$user_id,'欢迎登陆');
//        $this->message_api('1214',$user_id,'欢迎登陆');
        //$this->return = ['data'=>$data,'ret'=>'1001','code'=>'绑定成功'];
//        $data = $this->jiami($data);
//        $this->return = ['data' => $data];
    }

    /*
     * 发送消息接口
     */
    public function message()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');///获取数据包
        $get = $this->jiemi($get);///解密数据包
        $user_id = $get['user_id'];///当前用户id
        $receive_id = $get['receive_id'];///对方id
        $mark = $get['mark'];//有值为DME，没值为信用查

        if (empty($get['message'])) {
            $data['ret'] = '1002';
            $data['code'] = '消息内容不能为空，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $user_id, "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $gateway = new \Home\Service\Gateway();///workman库
        //$gateway = new \Org\Util\Gateway();
//        $user_name=M('user',Null,'DB2')->getFieldById($user_id,'username');
//        $receive_name=M('user',Null,'DB2')->getFieldById($receive_id,'username');
        if (empty($mark)) {//用户端发送消息
            $user_name = M('user', Null, 'DB2')->where(["id" => $user_id])->field("username,mobile,identity_num,shop_identifier")->find();
            $receive_name = M('communication', Null, 'DB2')->where(["account" => $receive_id])->field("nickname")->find();
            $u_name = $user_name["username"];
            $r_name = empty($receive_name["nickname"]) ? "" : $receive_name["nickname"];
            if (empty($user_name['username']) || empty($user_name['mobile']) || empty($user_name['identity_num'])) {
                $data['ret'] = '1002';
                $data['code'] = '请完善个人信息后发送，';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
        } else {//DME端发送消息
            $user_name = M('communication', Null, 'DB2')->where(["account" => $user_id])->field("nickname,shop_id")->find();
            $receive_name = M('user', Null, 'DB2')->where(["id" => $receive_id])->field("username")->find();
            $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["account" => $receive_id])->getField('name');
            $u_name = empty($user_name["nickname"]) ? "" : $user_name["nickname"];
            $r_name = empty($receive_name["username"]) ? "" : $receive_name["username"];
            if($shopkeeper){///内部同事聊天
                $shopkeeper_user_name = M('shopkeeper', Null, 'DB2')->where(["account" => $user_id])->getField('name');
                $u_name = empty($shopkeeper_user_name) ? "" : $shopkeeper_user_name;
                $r_name = empty($shopkeeper) ? "" : $shopkeeper;
            }
            $merchant_business_accont = M('merchant_business_accont', Null, 'DB2')->where(["keeper_id" => $user_name['shop_id']])->field("app_expire_time,acc_type")->find();
            if ($merchant_business_accont["acc_type"] == 1 && $merchant_business_accont["app_expire_time"] < time()) {//1普通账号，2免费账号
                $data['ret'] = '1002';
                $data['code'] = '该账号已过期或未购买';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }

        }
        $data["user_id"] = $get['user_id'];//发送人id
        $data["user_name"] = $u_name;///发送人姓名
        $data["receive_id"] = $get['receive_id'];//接收人id
        $data["receive_name"] = $r_name;///接收人姓名
        $data["message"] = $get['message'];//消息内容
        $data["type"] = $get['type'];//消息类型，1文字表情，2图片，3语音
        $data["send_time"] = time();//发送时间
        $data["voic_time"] = $get['voic_time'];//语音消息
        //$data=json_encode($data,JSON_UNESCAPED_UNICODE);


        if ($gateway->isUidOnline($receive_id) == 1) {///判断对方是否在线//1在线，0不在线

            if ($mark == 'qwerasd') {//是否有需要保存聊天记录,
                $chat_record = M('chat_record', Null, 'DB2')->add($data);
            } else {
                $chat_record = true;
            }

            if ($chat_record) {
                sleep(0.5);
                if ($gateway->isUidOnline($receive_id) == 0) {
                    M('chat_record_copy', Null, 'DB2')->add($data);
                } else {
                    //$data=json_encode($data);
                    $gateway->sendToUid($receive_id, json_encode($data)); //像对方发送消息
                }
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return true;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '消息发送失败';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
        } else {
            M('chat_record_copy', Null, 'DB2')->add($data);
            //M('chat_record', Null, 'DB2')->add($data);
            if ($mark == 'qwerasd') {//是否有需要保存聊天记录,
                M('chat_record', Null, 'DB2')->add($data);
            }
            if (empty($mark)) {//信用查
//                    $key="3b8810ed7cca6c75f782b371" ;
//                    $secret="8978f95a5d0ab168604f3787";

//                $key = "79e5e1d58d2b79d0c26e57cc";
//                $secret = "dcf8054db178401ccb01d48f";
                $merchant=M('merchant','','DB2')->where(['shop_identifier'=>$user_name['shop_identifier']])->field('jg_api,jg_secret')->find();
                $key =empty($merchant['jg_api'])?'':$merchant['jg_api'];
                $secret =empty($merchant['jg_secret'])?'':$merchant['jg_secret'];
            } else {//DME
//                    $key="79e5e1d58d2b79d0c26e57cc" ;
//                    $secret="dcf8054db178401ccb01d48f";
                $key = "79f71fd4299330b337db3a8a";
                $secret = "7c4ec03b7e98afac9f36b7be";
            }
            $app_key = $key; // appkey
            $master_secret = $secret; // master_secret
            $client = new \Home\Service\JPush\Client($app_key, $master_secret);
            $pusher = $client->push();
            $pusher->setPlatform(array('ios', 'android'));//选择平台
            $pusher->options(['apns_production' => false]);///开发环境
            $pusher->addAlias(trim($get['receive_id']));///单独推送
            if ($get['type'] == 2) {
                $get['message'] = "[图片]";
            }
            if ($get['type'] == 3) {
                $get['message'] = "[语音]";
            }
            $pusher->setNotificationAlert($u_name . '对你说"' . $get['message'] . '"');///推送消息
            try {
                $pusher->send();///开始推送
            } catch (\JPush\Exceptions\JPushException $e) {
                // try something else here
                print $e;
            }
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        }
    }
    /*
     * 发送消息封装方法
     */
    public function message_api($user_id, $receive_id, $message)
    {
        $gateway = new \Home\Service\Gateway();///workman库
        //$gateway = new \Org\Util\Gateway();
        $user_name = M('user', Null, 'DB2')->getFieldById($user_id, 'username');
        $receive_name = M('user', Null, 'DB2')->getFieldById($receive_id, 'username');

        $data["user_id"] = $user_id;//发送人id
        $data["user_name"] = $user_name;///发送人姓名
        $data["receive_id"] = $receive_id;//接收人id
        $data["receive_name"] = $receive_name;///接收人姓名
        $data["message"] = $message;//消息内容
        $data["type"] = '1';//消息类型，1文字表情，2图片，3语音
        $data["send_time"] = time();//发送时间
        $data["voic_time"] = '';//语音消息

        if ($gateway->isUidOnline($receive_id) == 1) {///判断对方是否在线1在线，2不在线

            $chat_record = M('chat_record', Null, 'DB2')->add($data);
            if ($chat_record) {
                $gateway->sendToUid($receive_id, json_encode($data)); //像对方发送消息

                $app_key = '79f71fd4299330b337db3a8a'; // appkey
                $master_secret = '7c4ec03b7e98afac9f36b7be'; // master_secret
                $client = new \Home\Service\JPush\Client($app_key, $master_secret);
                $pusher = $client->push();
                $pusher->setPlatform(array('ios', 'android'));//选择平台
                $pusher->options(['apns_production' => false]);///开发环境
                $pusher->addAlias(trim($receive_id));///单独推送
                $pusher->setNotificationAlert($message . '对你说"' . $message . '"');///推送消息
                try {
                    $pusher->send();///开始推送
                } catch (\JPush\Exceptions\JPushException $e) {
                    // try something else here
                    print $e;
                }
                $data['ret'] = '1001';
                $data['code'] = 'success';
//                        $data1 = $this->jiami($data);
                $this->return = ['data' => $data];
                return true;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '消息发送失败';
//                            $data1 = $this->jiami($data);
                $this->return = ['data' => $data];
                return false;
            }
        } else {
            $chat_record = M('chat_record_copy', Null, 'DB2')->add($data);
        }

    }

    public function message_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $user_id = $get['user_id'];///用户id
        $shop_idenfier = $get['shop_idenfier'];
        $customer = M('customer', '', C('DB2'))->where(array('shop_idenfier' => $shop_idenfier))->getField('user_id', true);
        $a = array_rand($customer, 1);
        $message_data = array(
            0 => array(
                'nickname' => '系统消息',
                'user_id' => '',
            ),
            1 => array(
                'nickname' => '还款提醒',
                'user_id' => '',
            ),
            2 => array(
                'nickname' => '客服',
                'user_id' => $a,
            ),
        );
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['data']['list'] = $message_data;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     *dme客服聊天登录
     */
    public function Dme_login()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get['account']) || empty($get['password']) || empty($get['shop_idenfier'])) {
            $data['ret'] = '1002';
            $data['code'] = '登录信息为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        //权限设置
        $shopkeeper_type = M('shopkeeper', Null, 'DB2')->where(["shop_idenfier" => $get['shop_idenfier'], "account" => $get['account'], "state" => 1])->field("id,rid")->find();

        //$shopkeeper_type = M('shopkeeper', Null, 'DB2')->where(["shop_idenfier" => $get['shop_idenfier'], "account" => $get['account'], "state" =>1])->field("id")->find();
        $merchant_business_accont = M('merchant_business_accont', Null, 'DB2')->where(['keeper_id' => $shopkeeper_type['id']])->field("acc_type,app_expire_time")->find();

        $account = $get['account'];///客服账号
        $password = $get['password'];///客服密码
        $shop_idenfier = $get['shop_idenfier'];///商家编号
        $password = md5($account . "xycshop" . $password);
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["shop_idenfier" => $shop_idenfier, "account" => $account,"state" => 1])->field("id,account,password,shop_idenfier,name,picture,mobile")->find();

        //(账号xycshop密码)
        //print_r($password);die;
        $data7["id"] = $shopkeeper["id"];//客服id
        $data7["name"] = $shopkeeper["name"];//姓名
        $data7["shop_idenfier"] = $shopkeeper["shop_idenfier"];//商户号
        $data7["picture"] = empty($shopkeeper["picture"]) ? "" : $shopkeeper["picture"];//头像
        $data7["mobile"] = $shopkeeper["mobile"];//手机

        if ($shopkeeper["account"] == $account
            && $shopkeeper["password"] == $password
            && $shopkeeper["shop_idenfier"] == $shop_idenfier) {
            if (empty($shopkeeper_type['id'])) {
                $data['ret'] = '1002';
                $data['code'] = '账号已被锁定或删除，请联系管理员';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
            if($get['shop_idenfier']!='0100030021'&&$get['shop_idenfier']!='0100010020'){
                $domain = strstr($shopkeeper_type['rid'], '4');//是否有客服角色权限
                $v2_domain = strstr($shopkeeper_type['rid'], '10');//是否有客服角色权限
                if (empty($domain)&&empty($v2_domain)) {
                    $data['ret'] = '1002';
                    $data['code'] = '该账号不是客服账号，无法登陆';
                    $data1 = $this->jiami($data);
                    $this->return = ['data' => $data1];
                    return false;
                }
            }

            if (empty($merchant_business_accont)) {
                $data['ret'] = '1002';
                $data['code'] = '该账号尚未购买,';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
            if ($merchant_business_accont['acc_type'] == 1 && $merchant_business_accont['app_expire_time'] < time()) {
                $data['ret'] = '1002';
                $data['code'] = '该账号已过期,请充值,';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data['data'] = $data7;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '登录信息错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * DME通讯录列表
     */
    public function DME_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => 1])->field("id,rid")->find();

        if (empty($shopkeeper)) {
            $data77["is_disable"] = "1";//1锁定强制退出//
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data['data'] = $data77;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $domain = strstr($shopkeeper['rid'], '4');
        $v2_domain = strstr($shopkeeper['rid'], '10');//是否有客服角色权限
        if (empty($domain)&&empty($v2_domain)) {
            $data77["is_disable"] = "1";//1锁定强制退出//
            $data['ret'] = '1002';
            $data['code'] = '账号角色发生变化,';
            $data['data'] = $data77;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get['user_id'])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get['shop_identifier'])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $limit = empty($get["limit"]) ? 10 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        $shop_identifier = $get["shop_identifier"];//商户号
        $status = $get["status"];//状态
        $user_id = $get["user_id"];//
//        $shop_identifier = '0100010020';//商户号
//        $status =1;//状态
//        $user_id = 46;//
        if ($status == 1) {
            $chat_record = M('user', Null, 'DB2')
                ->join("u left join user_identity uid on uid.user_id=u.id")
                ->where(["u.shop_identifier" => $shop_identifier, "u.cert_status" => 1, "u.chat_id" => $user_id])
                ->limit($page, $limit)
                ->order("u.ctime desc")
                ->field("u.id,u.username,u.picture,uid.hold")
                ->select();//未认证
        }
        if ($status == 2) {
            // $chat_user = M('certificate', Null, 'DB2')->where(["shop_identifier" => $shop_identifier])->field("id")->buildSql();
            $chat_record = M('user', Null, 'DB2')
                //->where(["shop_idenfier"=>$shop_idenfier,])
                // ->join("u left join certificate c on c.shop_identifier=u.shop_identifier and c.borrower_id=u.id")
                ->join("u left join certificate c on u.shop_identifier=c.shop_identifier")
                ->where(["u.cert_status" => 2, "u.chat_id" => $user_id, "c.borrower_id" => ["neq", "u.id"]])
                ->limit($page, $limit)
                ->order("u.ctime desc")
                ->field("u.id,u.username,u.picture,uid.hold")
                ->group("u.id")
                //->fetchSql(true)
                ->select();
        }
        if ($status == 3) {
            $c_status = ['in', '2,4,5,6,9'];//2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款

            $chat_record = M('user', Null, 'DB2')
                //->where(["shop_idenfier"=>$shop_idenfier,])
                ->join("u left join certificate c on c.shop_identifier=u.shop_identifier and c.borrower_id=u.id")
                ->join("left join user_identity uid on uid.user_id=u.id")
                ->where(["c.status" => $c_status, "c.is_delete" => 1, "u.chat_id" => $user_id])
                ->limit($page, $limit)
                ->order("u.ctime desc")
                ->field("u.id,u.username,u.picture,uid.hold")
                ->group("u.id")
                //->fetchSql(true)
                ->select();
            // print_r($chat_record);die;
        }
        if ($status == 4) {
            $chat_record = M('user', Null, 'DB2')
                //->where(["shop_idenfier"=>$shop_idenfier,])
                ->join("u left join certificate c on c.shop_identifier=u.shop_identifier and c.borrower_id=u.id")
                ->join("left join user_identity uid on uid.user_id=u.id")
                ->where(["c.status" => 3, "c.is_delete" => 1, "u.chat_id" => $user_id])
                ->limit($page, $limit)
                ->order("u.ctime desc")
                ->field("u.id,u.username,u.picture,uid.hold")
                ->group("u.id")
                //->fetchSql(true)
                ->select();
        }
        foreach ($chat_record as $kay => $value) {
            $chat_record[$kay]["picture"] = empty($value["picture"]) ? "" : $value["picture"];
            $chat_record[$kay]["hold"] = empty($value["hold"]) ? "" : $value["hold"];
        }
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($chat_record) ? 1 : 0;
        $data['page'] = (string)(count($chat_record) + $page);
        $data['data'] = $chat_record;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     * 通讯录用户详情
     */
    public function DME_Details()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        //权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get['id']) || empty($get['shop_identifier'])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $id = $get['id'];//通讯录列表id
        $shop_identifier = $get["shop_identifier"];//商户号

//        $id=40;//通讯录列表id
//        $shop_identifier='0100010020';//商户号
        $user = M('user', Null, 'DB2')->where(["id" => $id, "shop_identifier" => $shop_identifier])->field("username,mobile,picture,identity_num,address,sex,cert_status")->find();
        $user_identity = M('user_identity', Null, 'DB2')->where(["user_id" => $id, "shop_identifier" => $shop_identifier])->field("hold")->find();
        $user['picture'] = $user_identity['hold'];//用户头像
        $label_id = M('label', Null, 'DB2')
            ->join("l left join label_id l_id on l.id=l_id.label_id")
            ->where(["l_id.user_id" => $id, "l.shop_identifier" => $get["shop_identifier"], "l.is_dell" => 1])
            ->field("l.name")
            ->find();
        $user["name"] = empty($label_id["name"]) ? "" : $label_id["name"];//标签
        $user["mobile"] = empty($user["mobile"]) ? "" : substr_replace($user["mobile"], '*****', 3, 5);
        $user["identity_num"] = empty($user["identity_num"]) ? "" : substr_replace($user["identity_num"], '***********', 3, 11);

        //cert_status .1未认证2认证通过3认证拒绝 4其他认证中，5审核中
        switch ($user["cert_status"]) {
            case 1:
                $user["cert_status"] = "未认证";//1未认证，2已认证
                break;
            case 2:
                $user["cert_status"] = "认证通过";//1未认证，2已认证
                break;
            case 3:
                $user["cert_status"] = "认证拒绝";//1未认证，2已认证
                break;
            case 4:
                $user["cert_status"] = "其他认证中";//1未认证，2已认证
                break;
            case 5:
                $user["cert_status"] = "审核中";//1未认证，2已认证
                break;
        }
        if ($user["sex"] == 1) {
            $user["sex"] = "男";//1男，2女
        }
        if ($user["sex"] == 2) {
            $user["sex"] = "女";//1男，2女
        }
        if (empty($user["sex"])) {
            $user["sex"] = "未知";//1男，2女
        }
        if ($user) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data['data'] = $user;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '数据异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * DME 聊天记录接口
     */
    public function chatrecord_lsit()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get['user_id']) || empty($get['receive_id'])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        $user_id = $get['user_id'];
        $receive_id = $get['receive_id'];

//        $user_id=1147;
//        $receive_id=1140;
        $chat_record = M('chat_record', Null, 'DB2')
            ->where(["(user_id=" . '"' . $user_id . '"' . " or user_id=" . '"' . $receive_id . '"' . ")" . " and (receive_id=" . '"' . $user_id . '"' . " or receive_id=" . '"' . $receive_id . '"' . ")"])
            ->limit($page, $limit)
            ->order("send_time desc")
            ->select();

        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($chat_record) ? 1 : 0;
        $data['page'] = (string)(count($chat_record) + $page);
        $data['data'] = $chat_record;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     * DME凭证列表
     */
    public function DME_Certificate_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $user_id = $get["user_id"];///用户唯一标识
        if (empty($get["shop_identifier"]) || empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => 1])->field("id,rid")->find();
        if (empty($shopkeeper)) {
            $data77["is_disable"] = "1";//1锁定强制退出//
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data['data'] = $data77;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $domain = strstr($shopkeeper['rid'], '4');
        $v2_domain = strstr($shopkeeper['rid'], '10');//是否有客服角色权限
        if (empty($domain)&&empty($v2_domain)) {
            $data77["is_disable"] = "1";//1锁定强制退出//
            $data['ret'] = '1002';
            $data['code'] = '账号角色发生变化,';
            $data['data'] = $data77;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }

        $shop_identifier = $get["shop_identifier"];///商户号

        $status = $get["status"];//未确定，2已确认
//        $get["status"]=2;
//        $shop_identifier='0100010020';
//        $user_id=34;
        $limit = empty($get["limit"]) ? 10 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        if ($get["status"] == 2) {
            $status = ['in', '2,3,4,9'];//已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
        }

        if (empty($get["uid"])) {
            if ($get["status"] == 1) {
                $user_mob = M('certificate', Null, 'DB2')
                    ->join("c left join user u on c.borrower_id=u.id")
                    ->where(["c.shop_identifier" => $shop_identifier, "c.status" => $status, "c.is_delete" => 1, "u.chat_id" => $user_id, 'u.is_delete' => 1])
                    ->limit($page, $limit)->order("c.ctime desc")
                    ->field("c.lender,c.borrower,c.money,c.interest_rate,c.loan_type,c.status,c.loan_time,c.repayment_time,c.numbering,c.initiate_id,c.borrower_id")
                    //->fetchSql(true)
                    ->select();

            } else {
//            if ($get["status"] == 2) {
//                $status = ['in', '2,3,4,9'];//已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
//            }
                //$user_mob = M('certificate', Null, 'DB2')->where(["shop_identifier"=>$shop_identifier,"status"=>$status,"is_delete"=>1])->limit($page, $limit)->order("ctime desc")->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering,initiate_id,borrower_id")->select();
                $user_mob = M('certificate', Null, 'DB2')
                    ->join("c left join user u on c.borrower_id=u.id")
                    ->where(["c.shop_identifier" => $shop_identifier, "c.status" => $status, "c.is_delete" => 1, "u.chat_id" => $user_id, 'u.is_delete' => 1])
                    ->limit($page, $limit)->order("c.ctime desc")
                    ->field("c.lender,c.borrower,c.money,c.interest_rate,c.loan_type,c.status,c.loan_time,c.repayment_time,c.numbering,c.initiate_id,c.borrower_id")
                    //->fetchSql(true)
                    ->select();
            }
        } else {
            if ($get["status"] == 1) {
                $user_mob = M('certificate', Null, 'DB2')
                    ->join("c left join certificate_period cp on c.numbering=cp.numbering")
                    ->where(["c.borrower_id" => $get["uid"], "c.is_delete" => 1, "c.shop_identifier" => $get["shop_identifier"]])
                    ->where(["c.status=1 or cp.status=1"])
                    ->limit($page, $limit)
                    ->order("c.ctime desc")
                    ->field("c.lender,c.borrower,c.money,c.interest_rate,c.loan_type,c.status,c.loan_time,c.repayment_time,c.numbering,c.initiate_id,c.borrower_id,cp.status as ty_status")
                    ->select();
            } else {
//            if ($get["status"] == 2) {
//                $status = ['eq', '2,3,4,9'];//已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
//            }
                $user_mob = M('certificate', Null, 'DB2')->where(["status" => $status, "borrower_id" => $get["uid"], "is_delete" => 1, "shop_identifier" => $shop_identifier])->limit($page, $limit)->order("ctime desc")->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering,initiate_id,borrower_id")->select();
            }
        }
        //$user_mobb = M('certificate', Null, 'DB2')->where(["status" => $status, "lender_id" => $user_id])->order("ctime desc")->limit($page, $limit)->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering")->select();
        //$user_mob = M('certificate', Null, 'DB2')->where(["status" => $status, "borrower_id" => $user_id])->order("ctime desc")->limit($page, $limit)->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering")->select();
        //if ($user_mob) {
        // print_r($user_mob);die;

        foreach ($user_mob as $key => $value) {
            switch ($value["loan_type"]) {
                case 1:
                    $user_mob[$key]["loan_type"] = "日常消费";
                    break;
                case 2:
                    $user_mob[$key]["loan_type"] = "医疗";
                    break;
                case 3:
                    $user_mob[$key]["loan_type"] = "旅游";
                    break;
                case 4:
                    $user_mob[$key]["loan_type"] = "装修";
                    break;
                case 5:
                    $user_mob[$key]["loan_type"] = "教育";
                    break;
            }
            $user_mob[$key]["loan_type"] = empty($value["loan_type"]) ? "日常消费" : "日常消费";
            $user_mob[$key]["loan_time"] = date('Y-m-d', $value["loan_time"]);
            $user_mob[$key]["repayment_time"] = date('Y-m-d', $value["repayment_time"]);

            if ($get["status"] == 2) {
                $user_mob[$key]["status"] = $value["status"];///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if ($value["status"] == 9) {
                $user_mob[$key]["status"] = "2";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if (empty($value["ty_status"]) || $value["ty_status"] > 1) {
                $user_mob[$key]["ty_status"] = "1";//1为凭证2展期
            } else {
                $user_mob[$key]["ty_status"] = "2";///1为凭证2展期
            }

            if ($value["initiate_id"] == $user_id) {
                $user_mob[$key]["initiate_type"] = "2";///2发起人不能点击，1可以点击
            } else {
                $user_mob[$key]["initiate_type"] = "1";///2发起人不能点击，1可以点击
            }
            if ($value["borrower_id"] == $user_id) {
                $user_mob[$key]["type"] = "1";///1借款人 2出借人
            } else {
                $user_mob[$key]["type"] = "2";///1借款人 2出借人
            }
        }
        //if (!empty($user_mob)) {
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($user_mob) ? 1 : 0;
        $data['page'] = (string)(count($user_mob) + $page);
        $data['data'] = $user_mob;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;

    }

    /*
    * 凭证详情
    */
    public function DME_Certificate_Details()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $user_id = $get["user_id"];///用户唯一标识
        $dict["shop_identifier"] = $get["shop_identifier"];///安装包名
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单号错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $paypwd = M('user_login', Null, 'DB2')->where(["user_id" => $user_id, "shop_identifier" => $get["shop_identifier"], "status" => 1])->field("paypwd")->find();
        $user_mob = M('certificate', Null, 'DB2')->where(["numbering" => $get["numbering"], "shop_identifier" => $get["shop_identifier"]])->field("numbering,loan_time,repayment_time,money,interest_rate,interest,loan_type,status,lender,lender_signature,borrower,borrower_signature,borrower_id,lender,initiate_id")->find();
        switch ($user_mob["loan_type"]) {
            case 1:
                $user_mob["loan_type"] = "日常消费";
                break;
            case 2:
                $user_mob["loan_type"] = "医疗";
                break;
            case 3:
                $user_mob["loan_type"] = "旅游";
                break;
            case 4:
                $user_mob["loan_type"] = "装修";
                break;
            case 5:
                $user_mob["loan_type"] = "教育";
                break;
        }
//        if($user_mob["status"]=["in",2,3,4,9]){
//            $user_mob["status"] = "2";
//        }
        if ($user_mob["status"] == 9) {
            $user_mob["status"] = "2";
        }
        if ($user_mob["status"] == 4) {
            $user_mob["status"] = "2";
        }
        $user_mob["loan_type"] = empty($user_mob["loan_type"]) ? "日常消费" : "日常消费";
        if ($user_mob["borrower_id"] == $user_id) {
            $user_mob["type"] = "1";///1借款人 2出借人
        } else {
            $user_mob["type"] = "2";///1借款人 2出借人
        }
        if (!empty($paypwd)) {
            $user_mob["is_paypwd"] = "1";///1有支付密码2是没有支付密码
        } else {
            $user_mob["is_paypwd"] = "2";///1有支付密码2是没有支付密码
        }
        //initiate_id
        if ($user_mob["initiate_id"] == $user_id) {
            $user_mob["initiate_type"] = "2";///1可以点击2不能点击
        } else {
            $user_mob["initiate_type"] = "1";///1可以点击2不能点击
        }
        $user_mob["lender_status"] = empty($user_mob["lender_status"]) ? 0 : $user_mob["lender_status"];///借款人状态，1确认借条2发起展期
        $user_mob["borrower_status"] = empty($user_mob["borrower_status"]) ? 0 : $user_mob["borrower_status"];///借款人状态，1确认借款，2确认展期
        $user_mob["lender_avatar"] = '';///出借人头像
        $user_mob["borrower_avatar"] = '';///借款人头像
        $user_mob["service"] = '50';///服务费
        if (strtotime(date('Y-m-d')) < $user_mob["repayment_time"]) {
            $user_mob["overdue"] = 0;///逾期天数
        } else {
            $interest = (strtotime(date('Y-m-d')) - $user_mob["repayment_time"]) / 3600 / 24;///相差天数
            $user_mob["overdue"] = round($interest);///逾期天数
        }
        $user_mob["loan_time"] = date('Y-m-d', $user_mob["loan_time"]);
        $user_mob["repayment_time"] = date('Y-m-d', $user_mob["repayment_time"]);

        if ($user_mob) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data['data'] = $user_mob;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '凭证错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
* 拒绝借款接口
*/
    public function DME_Confirm_out()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $dict["shop_identifier"] = $get["shop_identifier"];///安装包名
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $user_id = $get["user_id"];///用户唯一标识
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单号错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        //"lender_id=" . $user_id . " or borrower_id=" . $user_id . ""
        //$user_mobb=M('certificate',Null,'DB2')->where(["numbering"=>$get["numbering"],"status"=>1,"lender_id"=>$user_id])->save(["utime"=>time(),"lender_status"=>2]);
        $data7["utime"] = time();
        $data7["status"] = 7;
        $user_mob = M('certificate', Null, 'DB2')->where(["shop_identifier" => $get["shop_identifier"], "numbering" => $get["numbering"], "status" => 1])->save($data7);

        if ($user_mob) {
            $this->DME_certificate_api($user_id, $get["numbering"]);
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '拒绝失败';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 凭证撕毁
     */
    public function DME_certificate_out()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $dict["shop_identifier"] = $get["shop_identifier"];///安装包名
        $user_id = $get["user_id"];///用户唯一标识
        $numbering = $get["numbering"];///订单号
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单号异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $certificate_period = M('certificate_period', Null, 'DB2');
        $certificate = M('certificate', Null, 'DB2');
        $certificate_data = M('certificate_data', Null, 'DB2');
        $nn_order = M('nn_order', Null, 'DB2');
        $certificate_period->startTrans();//开启事务
        $certificate->startTrans();//开启事务
        $certificate_data->startTrans();//开启事务
        $nn_order->startTrans();//开启事务

        $user_mob = M('certificate', Null, 'DB2')->where(["numbering" => $numbering, "status" => ["in", "2,3,4,9"]])->save(["utime" => time(), "tear_time" => time(), "status" => 6]);
        $certificate_period = M('certificate_period', Null, 'DB2')->where(["numbering" => $numbering, "status" => 1])->save(["utime" => time(), "status" => 3]);

//        $certificate_data =$certificate_data->where(['numbering'=>$numbering])->field('lender_mobile')->find();
//        $postdata['lenderMobile']=$certificate_data['lender_mobile'];
//        $order = M('nn_order','',C('DB2'))->where(['numbering'=>$numbering])->getField('nn_orderno');
//        $postdata['orderNo']=$order;
//        $url = 'http://www.hzdouniu.cn/api/xyc/tear_up_voucher';
//        $res = $this->get_curl($url,$postdata);
//        $res = json_decode($res,true);
//        if($res['resultCode']=='1000'){
//            $nn_order=$nn_order->where(['numbering'=>$numbering])->setField('status','4');
//        }
        //if ($user_mob&&$nn_order&&$certificate_period&&$certificate_data) {
        if ($user_mob) {
            $certificate_data = M('certificate_data', '', C('DB2'))->where(['numbering' => $numbering])->field('lender_mobile')->find();
            $postdata['lenderMobile'] = $certificate_data['lender_mobile'];
            $order = M('nn_order', '', C('DB2'))->where(['numbering' => $numbering])->getField('nn_orderno');
            $postdata['orderNo'] = $order;
            $postdata['tearupTime'] = time();
            $url = 'http://www.hzdouniu.cn/api/xyc/tear_up_voucher';
            $res = $this->get_curl($url, $postdata);
            $res = json_decode($res, true);
            if ($res['resultCode'] == '1000') {
                M('nn_order', '', C('DB2'))->where(['numbering' => $numbering])->setField('status', '4');
            }
            $now_status = M('certificate', Null, 'DB2')->where(["numbering" => $numbering, "status" => 3])->field('id,repayment_time,money')->find();
            if ($now_status) {
                $today = $now_status['repayment_time'] - strtotime('today');//今天整点时间戳
                $overdue_day = $today / 60 / 60 / 24;//逾期天数
            } else {
                $overdue_day = 0;
            }
            $zzc_up_data['user_id'] = $user_id;
            $zzc_up_data['orderno'] = $numbering;
            $zzc_up_data['type'] = $numbering;
            $zzc_up_data['ctime'] = time();
            $zzc_up_data['should_time'] = $now_status['repayment_time'];
            $zzc_up_data['should_repay_money'] = $now_status['money'];
            $zzc_up_data['real_repay_money'] = $now_status['money'];
            $zzc_up_data['overdue_day'] = $overdue_day;//is_over
            $zzc_up_data['is_over'] = 2;//2已经还清
            $zzc_up_data['type'] = 4;//4还款
            M('zzc_up_data_record', Null, 'DB2')->add($zzc_up_data);
//            $certificate_period->commit();//开启事务
//            $certificate->commit();//开启事务
//            $certificate_data->commit();//开启事务
//            $nn_order->commit();//开启事务
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;

        } else {
//            $certificate_period->rollback();//开启事务
//            $certificate->rollback();//开启事务
//            $certificate_data->rollback();//开启事务
//            $nn_order->rollback();//开启事务
            $data['ret'] = '1002';
            $data['code'] = '无法撕毁或已经撕毁';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 展期列表
     */
    public function DME_period_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("username")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $numbering = $get["numbering"];///订单号
        $limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        $certificate_period = M('certificate_period', Null, 'DB2')->where(["numbering" => $numbering])->limit($page, $limit)->field("id,numbering,money,status,period_time")->select();//总数
        foreach ($certificate_period as $kay => $value) {
            //$certificate_period[$kay]["repayment_time"]=date('Y-m-d',$value["repayment_time"]);
            $certificate_period[$kay]["period_time"] = date('Y-m-d', $value["period_time"]);
        }
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($certificate_period) ? 1 : 0;
        $data['page'] = (string)(count($certificate_period) + $page);
        $data['data'] = $certificate_period;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     * 展期详情
     */
    public function DME_period_Details()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["id"]) || empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $id = $get["id"];//展期列表
        $numbering = $get["numbering"];//订单号
        $certificate_period = M('certificate_period', Null, 'DB2')->where(["id" => $id, "numbering" => $numbering])->field("ctime,utime,shop_idenfier", true)->find();//总数
        $certificate_period["repayment_time"] = date('Y-m-d', $certificate_period["repayment_time"]);
        $certificate_period["period_time"] = date('Y-m-d', $certificate_period["period_time"]);
        if ($certificate_period) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data['data'] = $certificate_period;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '数据异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
  * 展期页面数据接口
  */
    public function DME_Renewal_data()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $dict["shop_identifier"] = $get["shop_identifier"];///安装包名
        $user_id = $get["user_id"];///用户唯一标识
        //权限
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $numbering = $get["numbering"];///订单号
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单号异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $user_mob = M('certificate', Null, 'DB2')->where(["shop_identifier" => $get["shop_identifier"], "numbering" => $numbering, "status" => ["in", "2, 3,4,9"]])->field("money,repayment_time,interest_rate,note,interest")->find();
        $user_mob["repayment_time"] = date('Y-m-d', $user_mob["repayment_time"]);
        if ($user_mob) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data['data'] = $user_mob;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '数据错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 展期提交接口
     */
    public function DME_Renewal()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $dict["shop_identifier"] = $get["shop_identifier"];///安装包名
        $user_id = $get["user_id"];///用户唯一标识
        $numbering = $get["numbering"];///订单号
        //权限
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单号异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        //$data["repayment_time"] =substr($get["repayment_time"] , 0 , 10);///新还款时间
        $user_mob = M('certificate', Null, 'DB2')->where(["status" => ["in", "2, 3,4,9"], "numbering" => $numbering])->field("repayment_time,money,interest,borrower_id")->find();
        $has_zq = M('certificate_period', '', 'DB2')->where(['numbering' => $numbering, 'status' => '1'])->getField('id');
        if ($has_zq) {
            $data['ret'] = '1002';
            $data['code'] = '还有未确认的展期，无法发起展期';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $interest_rate = $get["period_rate"] / 100;//年利率转换
        $Days = ($user_mob["money"] * $interest_rate) / 365;//日息价格
        $date = substr($get["repayment_time"], 0, 10);
        $interest = ($date - $user_mob["repayment_time"]) / 3600 / 24;///相差天数
        $Total_interest = $Days * $interest;///利息价格
        $data["interest"] = round($Total_interest, 2) + $user_mob["interest"];//本息共计
        //$data["lender_status"]=4;//出借人状态

        $data["shop_identifier"] = $get["shop_identifier"];///商户号
        $data["numbering"] = $get["numbering"];///订单号
        $data["period_days"] = $interest;///天数
        $data["borrower_id"] = $user_mob["borrower_id"];//借款人id period_days
        $data["money"] = $user_mob["money"];///本金
        $data["lender_id"] = $get["user_id"];///出借人id
        $data["interest_rate"] = $get["period_rate"];///年利率
        $data["interest"] = round($Total_interest, 2);///利息total
        //$data["total"] = round($Total_interest, 2) + $user_mob["interest"];///本息共计
        $data["ctime"] = time();
        $data["utime"] = time();
        $data["note"] = $get["note"];///备注
        $data["repayment_time"] = $user_mob["repayment_time"];///原还款日期
        $data["period_time"] = substr($get["repayment_time"], 0, 10);///展期时间
        $data["status"] = 1;///1未确认，2已确认，3已取消，
        if ($data["repayment_time"] > $data["period_time"]) {
            $data['ret'] = '1002';
            $data['code'] = '还款时间不能小于原还款日期。';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $user_mob = M('certificate_period', Null, 'DB2')->where(["numbering" => $numbering, "lender_id" => $user_id])->add($data);
        if ($user_mob && $user_mob) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '您不是借款人或已展期';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
    * 取消展期
    */
    public function DME_period_out()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $dict["shop_identifier"] = $get["shop_identifier"];///安装包名
        //权限
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $user_id = $get["user_id"];///用户唯一标识
        if (empty($get["user_id"]) || empty($get["id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单号异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $id = $get["id"];///"lender_id=" . $user_id . " or borrower_id=" . $user_id . ""
        $certificate_period = M('certificate_period', Null, 'DB2')->where(["numbering" => $get["numbering"], "id" => $id, "status" => 1])->save(["status" => 3, "utime" => time()]);//总数
        if ($certificate_period) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '你不是出借人或借款人，无法取消。';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * DME 个人信息接口
     */
    public function mine_index()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $id = $get["id"];
        $shop_identifier = $get["shop_identifier"];///安装包名

        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $id, "shop_identifier" => $shop_identifier, "status" => 1])->field("shop_idenfier,merchant_name,name,picture,mobile,email,rid")->find();
        $role = M('merchant_role', Null, 'DB2')->where(["id" => $shopkeeper["rid"], "status" => 1])->field("rolename")->find();
        $shopkeeper["role_name"] = empty($role["rolename"]) ? "未知" : $role["rolename"];//职务
        if ($shopkeeper) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data['data'] = $shopkeeper;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '数据异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 出借人列表接口
     */
    public function DME_lender_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $shop_identifier = $get["shop_identifier"];///安装包名

        $shopkeeper = M('lender', Null, 'DB2')->where(["shop_idenfier" => $shop_identifier, "is_delete" => 1])->field("id,name,signature")->select();
        if ($shopkeeper) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data['data'] = $shopkeeper;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '出借人数据异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 凭证分配出借人接口
     */
    public function DME_Certificate_select()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["numbering"])) {
            $data['ret'] = '1002';
            $data['code'] = '订单号错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["lender_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '出借人为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $lender_id = $get["lender_id"];
        $shop_identifier = $get["shop_identifier"];///安装包名
        $lender = M('lender', Null, 'DB2')->where(["id" => $lender_id, "shop_idenfier" => $shop_identifier, "is_delete" => 1])->field("id,name,signature")->find();
        $data7["utime"] = time();
        $data7["lender"] = $lender["name"];//出借人姓名
        $data7["lender_id"] = $lender["id"];//出借人id
        $data7["lender_signature"] = $lender["signature"];//出借人电子签名
        $data7["status"] = 2;//1未确认，2已确认
        $certificate = M('certificate', Null, 'DB2')->where(["status" => 1, "numbering" => $get["numbering"], "shop_identifier" => $shop_identifier, "is_delete" => 1, "lender_id" => ["eq", 0]])->save($data7);
        if ($certificate && $lender) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '添加出借人失败';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 新通讯录  新的朋友
     */
    public function new_friend()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登入';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $limit = empty($get["limit"]) ? 10 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        $shopkeeper = M('user', Null, 'DB2')->where(["shop_identifier" => $get["shop_identifier"], "chat_id" => $get["user_id"]])->order("ctime desc")->limit($page, $limit)->field("id,username")->select();
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($shopkeeper) ? 1 : 0;
        $data['page'] = (string)(count($shopkeeper) + $page);
        $data['data'] = $shopkeeper;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     *添加标签
     */
    public function label_add()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["name"])) {
            $data['ret'] = '1002';
            $data['code'] = '标签为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $data["name"] = $get["name"];//标签名
        $data["c_user_id"] = $get["user_id"];//用户id
        $data["shop_identifier"] = $get["shop_identifier"];//商户号
        $data["ctime"] = time();//创建时间
        $data["utime"] = time();//修改时间
        $label = M('label', Null, 'DB2')->where(['shop_identifier' => $get["shop_identifier"], 'name' => $get["name"]])->field('id')->find();
        if ($label) {
            $data['ret'] = '1002';
            $data['code'] = '标签已存在。';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        } else {
            $shopkeeper = M('label', Null, 'DB2')->add($data);
        }
        if ($shopkeeper) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '添加标签失败';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 标签列表
     */
    public function label_list()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
//        $get["shop_identifier"]='0100010020';
//        $get["user_id"]=59;
        $limit = empty($get["limit"]) ? 10 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        $label = M('label', Null, 'DB2')->where(["shop_identifier" => $get["shop_identifier"], "is_dell" => 1])->order("ctime desc")->limit($page, $limit)->field("id,name")->select();
        foreach ($label as $key => $value) {//user//label_id
//            $label_count = M('user', Null, 'DB2')
//                ->join("u LEFT  join label_id l on u.id=l.user_id")
//                ->where(["l.label_id" => $value["id"], "u.chat_id" => $get["user_id"],'u.is_delete'=>1,'u.shop_identifier'=>$get["shop_identifier"]])
//                ->group('u.id')
//                ->count();
            $label_count = M('user', Null, 'DB2')
                ->join("u left join label_id l on u.id=l.user_id")
                ->where(["l.label_id" => $value["id"], "u.chat_id" => $get["user_id"], 'u.is_delete' => 1, 'u.shop_identifier' => $get["shop_identifier"]])
                //->group('u.id')
                ->field('u.id')
                ->count();
            $label[$key]["label_count"] = empty($label_count) ? 0 : $label_count;//标签人数
        }
        //print_r($label_count);die;
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($label) ? 1 : 0;
        $data['page'] = (string)(count($label) + $page);
        $data['data'] = $label;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
    * 索引标签列表
    */
    public function index_label_list()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $label = M('label', Null, 'DB2')->where(["shop_identifier" => $get["shop_identifier"], "is_dell" => 1])->order("name desc")->field("id,name")->select();
        foreach ($label as $key => $value) {
            $label_count = M('label_id', Null, 'DB2')->where(["label_id" => $value["id"]])->count();
            $label[$key]["label_count"] = $label_count;//标签人数
        }
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($label) ? 1 : 0;
//        $data['page'] = (string)(count($label) + $page);
        $data['data'] = $label;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     * 修改标签
     */
    public function label_updata()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["id"])) {
            $data['ret'] = '1002';
            $data['code'] = '标签异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["name"])) {
            $data['ret'] = '1002';
            $data['code'] = '标签不能为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $data["name"] = $get["name"];//标签名
        $data["u_user_id"] = $get["user_id"];//修改人id
        $data["utime"] = time();//修改时间
        $label_ = M('label', Null, 'DB2')->where(['shop_identifier' => $get["shop_identifier"], 'name' => '无标签', 'is_dell' => 1])->field('id')->find();
        if ($label_['name'] == $get["name"]) {
            $data['ret'] = '1002';
            $data['code'] = '默认标签无法修改,';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $label_fint = M('label', Null, 'DB2')->where(['shop_identifier' => $get["shop_identifier"], 'name' => $get['name'], 'is_dell' => 1])->field('id')->find();
        if ($label_fint) {
            $data['ret'] = '1002';
            $data['code'] = '标签名不能重复,';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        } else {
            $label = M('label', Null, 'DB2')->where(["id" => $get["id"], "shop_identifier" => $get["shop_identifier"], "is_dell" => 1])->save($data);
        }

        //$label = M('label', Null, 'DB2')->where(["id" => $get["id"], "shop_identifier" => $get["shop_identifier"], "is_dell" => 1])->save($data);
        if ($label) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '标签修改失败';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 删除标签
     */
    public function label_dell()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["id"])) {
            $data['ret'] = '1002';
            $data['code'] = '标签异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $data["u_user_id"] = $get["user_id"];//修改人id
        $data["utime"] = time();//修改时间
        $data["is_dell"] = 2;
        $label_find = M('label', Null, 'DB2')->where(["shop_identifier" => $get["shop_identifier"], "is_dell" => 1, 'name' => '无标签'])->field('id')->find();
        if ($label_find['id'] == $get["id"]) {
            $data['ret'] = '1002';
            $data['code'] = '默认标签不可删除。';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        M('label', Null, 'DB2')->startTrans();//开启事物操作
        M('label_id', Null, 'DB2')->startTrans();//开启事物操作
        $label = M('label', Null, 'DB2')->where(["id" => $get["id"], "shop_identifier" => $get["shop_identifier"], "is_dell" => 1])->save($data);
        $label_count = M('label_id', Null, 'DB2')->where(["label_id" => $get["id"]])->field('id')->find();
        if ($label_count) {
            $label_id = M('label_id', Null, 'DB2')->where(["label_id" => $get["id"]])->save(['label_id' => $label_find['id'], 'utime' => time()]);
            if ($label && $label_id) {
                M('label', Null, 'DB2')->commit();//提交
                M('label_id', Null, 'DB2')->commit();//提交
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return true;
            } else {
                M('label', Null, 'DB2')->rollback();//回滚
                M('label_id', Null, 'DB2')->rollback();//回滚
                $data['ret'] = '1002';
                $data['code'] = '标签删除失败';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
        } else {
            if ($label) {
                M('label', Null, 'DB2')->commit();//提交
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return true;
            } else {
                M('label', Null, 'DB2')->rollback();//回滚
                $data['ret'] = '1002';
                $data['code'] = '标签删除失败';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
        }

    }

    /*
     * 给用户添加标签接口
     */
    public function user_label_add()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["id"])) {
            $data['ret'] = '1002';
            $data['code'] = '标签异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["uid"])) {
            $data['ret'] = '1002';
            $data['code'] = '用户异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $data["user_id"] = $get["uid"];//用户id
        $data["label_id"] = $get["id"];//标签id
        $data["ctime"] = time();//创建时间
        $label_id = M('label_id', Null, 'DB2')->where(["user_id" => $get["uid"]])->field("id")->find();
        if ($label_id) {
            $label_id = M('label_id', Null, 'DB2')->where(["user_id" => $get["uid"]])->save(["label_id" => $get["id"], "utime" => time()]);
        } else {
            $label_id = M('label_id', Null, 'DB2')->add($data);
        }
        if ($label_id) {
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '添加标签失败';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * DME新通讯录
     */
    public function new_record_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
//        $get["user_id"]=34;
//            $get["shop_identifier"]='0100010020';
        $limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        $chat_id = $get["user_id"];
        $label = M('user', Null, 'DB2')
            ->join("u left join label_id l_id on u.id=l_id.user_id")
            ->join("left join label l on l.id=l_id.label_id")
            ->join("left join user_chat_now uc on uc.chat_id=$chat_id")
            ->join("left join user_identity uid on uid.user_id=u.id")
            // "l_id.user_id" => ["gt", 0],
            ->where(["l.shop_identifier" => $get["shop_identifier"], "l.is_dell" => 1, "u.chat_id" => $get["user_id"], 'u.is_delete' => 1])
            ->order("l.name desc,u.ctime desc")
            ->limit($page, $limit)
            ->field("l.id,l_id.user_id,l.name,u.username,uid.hold")
            ->group("u.id")
            //->fetchSql(true)
            ->select();
        foreach ($label as $key=>$value){
            $label[$key]['username']=empty($value['username'])?'':empty($value['username']);
        }
        //print_r($label);die;
        //$label["name"]=$label;
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($label) ? 1 : 0;
        $data['page'] = (string)(count($label) + $page);
        $data['data'] = $label;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     * WEB DME新通讯录
     */
    public function web_new_record_list()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
//        $get["user_id"]=34;
//            $get["shop_identifier"]='0100010020';
        //$limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        //$page = empty($get["page"]) ? 0 : $get["page"];//页数
        $chat_id = $get["user_id"];

        $label = M('user', Null, 'DB2')
            ->join("u left join label_id l_id on u.id=l_id.user_id")
            ->join("left join label l on l.id=l_id.label_id")
            ->join("left join user_chat_now uc on uc.chat_id=$chat_id")
            ->join("left join user_identity uid on uid.user_id=u.id")
            ->where(["l.shop_identifier" => $get["shop_identifier"], "l.is_dell" => 1, "u.chat_id" => $get["user_id"], 'u.is_delete' => 1])
            ->order("l.name desc,u.ctime desc")
            //->limit($page, $limit)
            ->field("l.id,l_id.user_id,l.name,u.username,uid.hold")
            ->group("u.id")
            //->fetchSql(true)
            ->select();
        //print_r($label);die;
        //$label["name"]=$label;
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($label) ? 1 : 0;
        //$data['page'] = (string)(count($label) + $page);
        $data['data'] = $label;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }
    /*
     * 新通讯录搜索
     */
    public function new_record_search()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        $search=$get['search'];
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if(empty($get["shop_identifier"])){
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
//        $get["user_id"]=11;
//        $get["shop_identifier"]='0100010020';
//        $search='彭';
        $data1['instr(u.username,"'.$search.'")']=['gt',0];//模糊查询

        $label = M('user', Null, 'DB2')
            ->join("u left join label_id l_id on u.id=l_id.user_id")
            ->join("left join label l on l.id=l_id.label_id")
            ->join("left join user_identity uid on uid.user_id=u.id")
            // "l_id.user_id" => ["gt", 0],
            ->where($data1)
            ->where(["l.shop_identifier" => $get["shop_identifier"], "l.is_dell" => 1, "u.chat_id" => $get["user_id"], 'u.is_delete' => 1])
            ->order("l.name desc")
            //->limit($page, $limit)
            ->field("l.id,l_id.user_id,l.name,u.username,uid.hold")
            //->group("u.id")
            //->fetchSql(true)
            ->select();
        foreach ($label as $key=>$value){
            $label[$key]['hold']=empty($value['hold'])?'':$value['hold'];
            $label[$key]['username']=empty($value['username'])?'':$value['username'];
        }
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($label) ? 1 : 0;
        //$data['page'] = (string)(count($label) + $page);
        $data['data'] = $label;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }
    /*
     *
     */
    public function  jiemimi(){
        $get = I('data');
        $get = $this->jiemi($get);
        print_r($get);
    }

    /**
     * @param string $url 上传地址
     * @param array $data 上传数组
     * @param string $header 头文件设置
     */
    public function set_curl($url, $data = array(), $header = '')
    {
        $ch = curl_init();
        if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, '1');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        if (curl_error($ch)) {
            return '错误信息:' . curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }

    static function cl_sms($mobile, $content, $shop_identifier)
    {
        date_default_timezone_set('PRC');//设置时区
//        $mobile=I('mobile');
//        $shop_identifier=I('shop_identifier');
        $url = 'https://smssh1.253.com/msg/send/json';
        $data['account'] = 'N3075640';
        $data['password'] = 'C8gWliKHwneaf5';
        $app_name = M('merchant', '', C('DB2'))->where(['shop_identifier' => $shop_identifier])->getField('merchant_name');
//        $data['msg'] = '【'.$app_name.'】' . $content;
        $data['msg'] = '【信用查】' . $content;
        $data['phone'] = $mobile;
        $data['sendtime'] = date('YmdHi');
        $data['report'] = 'true';
        $header = array('Content-Type:application/json;charset=utf-8');
        $result = self::set_curl($url, json_encode($data), $header);
        $res = json_decode($result, true);
        if ($res['code'] == '0') {
//            $add= array(
//                'shop_identifier'=>$shop_identifier,
//                'mobile'=>$mobile,
//                'money'=>'0.05',
//                'detail'=>'修改交易密码获取短信',
//                'type'=>'1',
//                'ctime'=>time(),
//            );
//            M('balance_record','',C('DB2'))->add($add);
//            M('merchant','',C('DB2'))->where(array('shop_identifier'=>$shop_identifier))->setDec('msg_balance',0.05);
            $add_news = array(
                'shop_identifier' => $shop_identifier,
                'mobile' => $mobile,
                'result' => '1001',
                'ctime' => time(),
                'content' => $content,
            );
            M('user_sms_record', '', C('DB2'))->add($add_news);
            return true;
        } else {
            $add_news = array(
                'shop_identifier' => $shop_identifier,
                'mobile' => $mobile,
                'result' => $res['errorMsg'],
                'ctime' => time(),
                'content' => $content,
            );
            M('user_sms_record', '', C('DB2'))->add($add_news);
            return $res['errorMsg'];
        }
    }

    /// 找回密码
    public function backpwd_code()
    {
        header("Content-Type: text/html; charset=UTF-8");
        $data1 = I('data');
        $get = $this->jiemi($data1);
        $mobile = $get['mobile'];
        $shop_identifier = $get['shop_identifier'];
        $res = M('shopkeeper', Null, 'DB2')->where(array('mobile' => $mobile, 'shop_idenfier' => $shop_identifier))->field('id')->find();
        if (!preg_match("/1[34578]{1}\d{9}$/", $mobile)) {
            $data['ret'] = '1002';
            $data['code'] = '手机号码格式不正确';
            $data = $this->jiami($data);
            $this->return = ['data' => $data];
            exit();
        }
        if (empty($res)) {
            $data['ret'] = '1002';
            $data['code'] = '手机号不存在';
            $data['zhuagntai'] = $res;
            $data['zhuangtai1'] = $mobile;
            $data = $this->jiami($data);
            $this->return = ['data' => $data];
            exit();
        }
        $phonecode = rand(100000, 999999);
        $time = S($mobile, 'backpwd_time');
        if (time() - $time > 59) {
            S($mobile . 'backpwd_verify', $phonecode);
            S($mobile . 'backpwd_time', time());
            $content = '验证码为' . $phonecode . ',您正在找回密码，请勿将验证码透露给他人。';
            $status = $this->cl_sms($mobile, $content, $shop_identifier);
            if ($status) {
                $add = array(
                    'shop_identifier' => $shop_identifier,
                    'mobile' => $mobile,
                    'money' => '0.05',
                    'detail' => '修改密码获取短信',
                    'type' => '1',
                    'ctime' => time(),
                );
                M('balance_record', '', C('DB2'))->add($add);
                M('merchant', '', C('DB2'))->where(array('shop_identifier' => $shop_identifier))->setDec('msg_balance', 0.05);
                $data['ret'] = '1001';
                $data['code'] = '短信已成功发送,请注意查收';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                exit;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '发送失败,请联系管理员';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                exit;
            }
        } else {
            $data['ret'] = '1002';
            $data['code'] = '验证短信之间发送间隔为3分钟，且每日只能发送5条';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            exit;
        }
    }

    /*
  *DME忘记密码接口
  */
    public function DME_forget_password()
    {

        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get['account']) || empty($get['shop_idenfier'])) {
            $data['ret'] = '1002';
            $data['code'] = '信息为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (!preg_match("/1[345678]{1}\d{9}$/", $get['mobile'])) {
            $data['ret'] = '1002';
            $data['code'] = '手机号格式错误';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get['code'])) {
            $data['ret'] = '1002';
            $data['code'] = '验证码为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["shop_idenfier" => $get['shop_idenfier'], "account" => $get['account'], "state" => 1, "mobile" => $get["mobile"]])->field("id,password")->find();
        if (empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '没有找到该账号';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        } else {
            $mobile = $get["mobile"];///手机号
            $code = $get["code"];//验证码
            $password = $get["password"];//新密码
            $test_password = $get["test_password"];//确认新密码
            $account = $get["account"];
            if ($password != $test_password) {
                $data['ret'] = '1002';
                $data['code'] = '确认密码不相同';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
            $password = md5($account . "xycshop" . $password);
            if ($shopkeeper["password"] == $password) {
                $data['ret'] = '1002';
                $data['code'] = '新旧密码相同';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
            $time = S($mobile . 'backpwd_time');
            $redcode = S($mobile . 'backpwd_verify');
            if (time() - $time > 120 || $redcode != $code) {
//                $data['ret']='1002';
//                $data['code']='验证码错误';
//                echo json_encode($data);
//                return false;
                $data['ret'] = '1002';
                $data['code'] = '验证码错误';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
            $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["shop_idenfier" => $get['shop_idenfier'], "account" => $get['account'], "state" => 1, "mobile" => $get["mobile"]])->save(["password" => $password]);
            if ($shopkeeper) {
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '修改失败';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return false;
            }
        }
    }

    /*
     *标签中用户列表
     */
    public function DME_label_user_lsit()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["id"])) {
            $data['ret'] = '1002';
            $data['code'] = '标签异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        $label_id = M('label_id', Null, 'DB2')
            ->join("l left join user u on u.id=l.user_id")
            ->join("left join user_identity uid on uid.user_id=u.id")
            ->where(["l.label_id" => $get["id"], "u.chat_id" => $get["user_id"], 'u.is_delete' => 1])
            ->field("u.username,u.id,uid.hold")
            ->limit($page, $limit)
            ->group('u.id')
            ->order("l.ctime desc")
            ->select();
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($label_id) ? 1 : 0;
        $data['page'] = (string)(count($label_id) + $page);
        $data['data'] = $label_id;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     * 近三天新的朋友
     */
    public function new_friend_user()
    {
        header("Access-Control-Allow-Origin: *");
        $get = I('data');
        $get = $this->jiemi($get);
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登入';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => 1])->field("id")->find();
        if (empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["shop_identifier"])) {
            $data['ret'] = '1002';
            $data['code'] = '商户号为空';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }

        //$get["user_id"]='59';
        $limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数
        //$todaytime = strtotime("today");
//        $time = time() - 2592000;//30天
        $shopkeeper = M('user', Null, 'DB2')
            ->join("u left join user_identity uid on uid.user_id=u.id")
            ->where(["u.chat_id" => $get["user_id"], 'u.is_delete' => 1])
            ->order("u.ctime desc")
            ->limit($page, $limit)
            ->field("u.id as user_id,u.username,uid.hold")
            ->group("u.id")
            //   ->fetchSql(true)
            ->select();
        //print_r($shopkeeper);die;

        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($shopkeeper) ? 1 : 0;
        $data['page'] = (string)(count($shopkeeper) + $page);
        $data['data'] = $shopkeeper;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
        * 用户凭证列表
        */
    public function user_Certificate_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $user_id = $get["user_id"];///用户唯一标识
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登入';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["uid"])) {
            $data['ret'] = '1002';
            $data['code'] = '用户异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $dict["shop_identifier"] = $get["shop_identifier"];///渠道

        $status = $get["status"];//未确定，2已确认
        $limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        $page = empty($get["page"]) ? 0 : $get["page"];//页数

        if ($get["status"] == 2) {
            $status = ['in', '2,3,4,9'];//已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
        }
        if ($get["status"] == 1) {
            $user_mob = M('certificate', Null, 'DB2')
                ->join("c left join certificate_period cp on c.numbering=cp.numbering")
                ->where(["c.borrower_id" => $get["uid"], "is_delete" => 1])
                ->where(["c.status=1 or cp.status=1", "shop_identifier" => $get["shop_identifier"]])
                ->limit($page, $limit)
                ->order("c.ctime desc")
                ->field("c.lender,c.borrower,c.money,c.interest_rate,c.loan_type,c.status,c.loan_time,c.repayment_time,c.numbering,c.initiate_id,c.borrower_id,cp.status as ty_status")
                ->select();
        } else {
//            if ($get["status"] == 2) {
//                $status = ['eq', '2,3,4,9'];//已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
//            }
            $user_mob = M('certificate', Null, 'DB2')->where(["status" => $status, "borrower_id" => $get["uid"], "is_delete" => 1, "shop_identifier" => $get["shop_identifier"]])->limit($page, $limit)->order("ctime desc")->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering,initiate_id,borrower_id")->select();
        }
        //$user_mobb = M('certificate', Null, 'DB2')->where(["status" => $status, "lender_id" => $user_id])->order("ctime desc")->limit($page, $limit)->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering")->select();
        //$user_mob = M('certificate', Null, 'DB2')->where(["status" => $status, "borrower_id" => $user_id])->order("ctime desc")->limit($page, $limit)->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering")->select();
        //if ($user_mob) {
        foreach ($user_mob as $key => $value) {
            switch ($value["loan_type"]) {
                case 1:
                    $user_mob[$key]["loan_type"] = "日常消费";
                    break;
                case 2:
                    $user_mob[$key]["loan_type"] = "医疗";
                    break;
                case 3:
                    $user_mob[$key]["loan_type"] = "旅游";
                    break;
                case 4:
                    $user_mob[$key]["loan_type"] = "装修";
                    break;
                case 5:
                    $user_mob[$key]["loan_type"] = "教育";
                    break;
            }
            $user_mob[$key]["loan_type"] = empty($value["loan_type"]) ? "日常消费" : "日常消费";
            $user_mob[$key]["loan_time"] = date('Y-m-d', $value["loan_time"]);
            $user_mob[$key]["repayment_time"] = date('Y-m-d', $value["repayment_time"]);

//            if($get["status"]==1){
//                $user_mob[$key]["status"] = "1";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
//            }
            if ($get["status"] == 2) {
                $user_mob[$key]["status"] = "2";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if ($value["status"] == 4) {
                $user_mob[$key]["status"] = "2";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if ($value["status"] == 9) {
                $user_mob[$key]["status"] = "2";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if ($value["status"] == 3) {
                $user_mob[$key]["status"] = $value["status"];///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if (empty($value["ty_status"]) || $value["ty_status"] > 1) {
                $user_mob[$key]["ty_status"] = "1";//1为凭证2展期
            } else {
                $user_mob[$key]["ty_status"] = "2";///1为凭证2展期
            }
//            if ($value["status"] = ["eq", '2,3,4,9']) {
//
//            }
            // else {
////                $user_mob[$key]["status"] = $value["status"];
////            }
////            if ($value["status"] == 1) {
////                $user_mob[$key]["status"] = "1";
////            }

            if ($value["initiate_id"] == $user_id) {
                $user_mob[$key]["initiate_type"] = "2";///2发起人不能点击，1可以点击
            } else {
                $user_mob[$key]["initiate_type"] = "1";///2发起人不能点击，1可以点击
            }
            if ($value["borrower_id"] == $user_id) {
                $user_mob[$key]["type"] = "1";///1借款人 2出借人
            } else {
                $user_mob[$key]["type"] = "2";///1借款人 2出借人
            }
        }

        //if (!empty($user_mob)) {
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($user_mob) ? 1 : 0;
        $data['page'] = (string)(count($user_mob) + $page);
        $data['data'] = $user_mob;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;

    }
    /*
     * WEB新通讯录
     */
    public function web_user_Certificate_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $user_id = $get["user_id"];///用户唯一标识
        if (empty($get["user_id"])) {
            $data['ret'] = '1002';
            $data['code'] = '请先登入';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        ///权限判断
        $shopkeeper = M('shopkeeper', Null, 'DB2')->where(["id" => $get['user_id'], "state" => ["neq", 1]])->field("id")->find();
        if (!empty($shopkeeper)) {
            $data['ret'] = '1002';
            $data['code'] = '账号已被锁定或删除，请联系管理员';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($get["uid"])) {
            $data['ret'] = '1002';
            $data['code'] = '用户异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $dict["shop_identifier"] = $get["shop_identifier"];///渠道

        $status = $get["status"];//未确定，2已确认
        //$limit = empty($get["limit"]) ? 6 : $get["limit"];//条数
        //$page = empty($get["page"]) ? 0 : $get["page"];//页数

        if ($get["status"] == 2) {
            $status = ['in', '2,3,4,9'];//已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
        }
        if ($get["status"] == 1) {
            $user_mob = M('certificate', Null, 'DB2')
                ->join("c left join certificate_period cp on c.numbering=cp.numbering")
                ->where(["c.borrower_id" => $get["uid"], "is_delete" => 1])
                ->where(["c.status=1 or cp.status=1", "shop_identifier" => $get["shop_identifier"]])
                //->limit($page, $limit)
                ->order("c.ctime desc")
                ->field("c.lender,c.borrower,c.money,c.interest_rate,c.loan_type,c.status,c.loan_time,c.repayment_time,c.numbering,c.initiate_id,c.borrower_id,cp.status as ty_status")
                ->select();
        } else {
//            if ($get["status"] == 2) {
//                $status = ['eq', '2,3,4,9'];//已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
//            }
            $user_mob = M('certificate', Null, 'DB2')->where(["status" => $status, "borrower_id" => $get["uid"], "is_delete" => 1, "shop_identifier" => $get["shop_identifier"]])->order("ctime desc")->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering,initiate_id,borrower_id")->select();
        }
        //$user_mobb = M('certificate', Null, 'DB2')->where(["status" => $status, "lender_id" => $user_id])->order("ctime desc")->limit($page, $limit)->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering")->select();
        //$user_mob = M('certificate', Null, 'DB2')->where(["status" => $status, "borrower_id" => $user_id])->order("ctime desc")->limit($page, $limit)->field("lender,borrower,money,interest_rate,loan_type,status,loan_time,repayment_time,numbering")->select();
        //if ($user_mob) {
        foreach ($user_mob as $key => $value) {
            switch ($value["loan_type"]) {
                case 1:
                    $user_mob[$key]["loan_type"] = "日常消费";
                    break;
                case 2:
                    $user_mob[$key]["loan_type"] = "医疗";
                    break;
                case 3:
                    $user_mob[$key]["loan_type"] = "旅游";
                    break;
                case 4:
                    $user_mob[$key]["loan_type"] = "装修";
                    break;
                case 5:
                    $user_mob[$key]["loan_type"] = "教育";
                    break;
            }
            $user_mob[$key]["loan_type"] = empty($value["loan_type"]) ? "日常消费" : "日常消费";
            $user_mob[$key]["loan_time"] = date('Y-m-d', $value["loan_time"]);
            $user_mob[$key]["repayment_time"] = date('Y-m-d', $value["repayment_time"]);

//            if($get["status"]==1){
//                $user_mob[$key]["status"] = "1";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
//            }
            if ($get["status"] == 2) {
                $user_mob[$key]["status"] = "2";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if ($value["status"] == 4) {
                $user_mob[$key]["status"] = "2";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if ($value["status"] == 9) {
                $user_mob[$key]["status"] = "2";///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if ($value["status"] == 3) {
                $user_mob[$key]["status"] = $value["status"];///2已确认,3已逾期,4续期,5已作废,6已撕毁,7被拒绝9已打款
            }
            if (empty($value["ty_status"]) || $value["ty_status"] > 1) {
                $user_mob[$key]["ty_status"] = "1";//1为凭证2展期
            } else {
                $user_mob[$key]["ty_status"] = "2";///1为凭证2展期
            }
//            if ($value["status"] = ["eq", '2,3,4,9']) {
//
//            }
            // else {
////                $user_mob[$key]["status"] = $value["status"];
////            }
////            if ($value["status"] == 1) {
////                $user_mob[$key]["status"] = "1";
////            }

            if ($value["initiate_id"] == $user_id) {
                $user_mob[$key]["initiate_type"] = "2";///2发起人不能点击，1可以点击
            } else {
                $user_mob[$key]["initiate_type"] = "1";///2发起人不能点击，1可以点击
            }
            if ($value["borrower_id"] == $user_id) {
                $user_mob[$key]["type"] = "1";///1借款人 2出借人
            } else {
                $user_mob[$key]["type"] = "2";///1借款人 2出借人
            }
        }
        //if (!empty($user_mob)) {
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($user_mob) ? 1 : 0;
        //$data['page'] = (string)(count($user_mob) + $page);
        $data['data'] = $user_mob;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;

    }
    /*
     * 凭证推送消息api
     */
    public function certificate_api()
    {
        $receive_id = I('receive_id');
        $numbering = I('numbering');
        if (empty($receive_id)) {
            $data['ret'] = '1002';
            $data['code'] = '接收人id为空';
            $this->return = ['data' => $data];
            return false;
        }
        if (empty($numbering)) {
            $data['ret'] = '1002';
            $data['code'] = '订单号为空';
            $this->return = ['data' => $data];
            return false;
        }
        $gateway = new \Home\Service\Gateway();

        $certificate = M('certificate', Null, 'DB2')->where(['borrower_id' => $receive_id, 'numbering' => $numbering, 'is_delete' => 1])
            ->field('numbering,loan_time,repayment_time,money,interest_rate,loan_type,borrower,status')->find();//待还总金额
        if (empty($certificate)) {
            $data['ret'] = '1002';
            $data['code'] = '订单异常';
            $this->return = ['data' => $data];
            return true;
        }
        if($certificate["status"]==9){
            $certificate["status"] = "2";
        }
//
//        $data['numbering']='P2018153291388691915924w';//订单号
//        //$data['initiate_id']='80';
//        $data['loan_time']=time();//借款时间
//        $data['repayment_time']=time();//还款时间
//        $data['money']=1000;//借款金额
//        $data['interest_rate']=10;//年利率
//        $data['loan_type']='日常消费';
//        $data['borrower']='借款人';
//        $data['status']=2;
        switch ($certificate["loan_type"]) {
            case 1:
                $certificate["loan_type"] = '日常消费';
                break;
            case 2:
                $certificate["loan_type"] = '医疗';
                break;
            case 3:
                $certificate["loan_type"] = '旅游';
                break;
            case 4:
                $certificate["loan_type"] = '装修';
                break;
            case 5:
                $certificate["loan_type"] = '教育';
                break;
            default:
                $certificate["loan_type"] = '日常消费';
                break;
        }
        $data7["user_id"] = "5";//发送人id
        $data7["user_name"] = "系统消息";//发送人姓名
        $data7["receive_id"] = $receive_id;//接收人id
        $data7["receive_name"] = $certificate['borrower'];//接收人姓名
        $data7["message"] = json_encode($certificate);//消息内容
        $data7["send_time"] = time();
        $data7["type"] = 4;//1语音消息2图片3语音,4凭证，5订单，
        $data7["voic_time"] = 0;//语音时长
        $data77 = json_encode($data7, JSON_UNESCAPED_UNICODE);

        if ($gateway->isUidOnline($receive_id) == 1) {
            $gateway->sendToUid($receive_id, $data77);
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $this->return = ['data' => $data];
            return true;
        } else {
            $chat_record_copy = M('chat_record_copy', Null, 'DB2')->add($data7);
            if ($chat_record_copy) {
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $this->return = ['data' => $data];
                return true;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '发送失败';
                $this->return = ['data' => $data];
                return false;
            }
        }
    }
    /*
* 凭证推送消息api
*/
    public function certificate_api1($receive_id,$numbering)
    {
//        $receive_id = I('receive_id');
//        $numbering = I('numbering');
        if (empty($receive_id)) {
            $data['ret'] = '1002';
            $data['code'] = '接收人id为空';
            $this->return = ['data' => $data];
            return false;
        }
        if (empty($numbering)) {
            $data['ret'] = '1002';
            $data['code'] = '订单号为空';
            $this->return = ['data' => $data];
            return false;
        }
        $gateway = new \Home\Service\Gateway();

        $certificate = M('certificate', Null, 'DB2')->where(['borrower_id' => $receive_id, 'numbering' => $numbering, 'is_delete' => 1])
            ->field('numbering,loan_time,repayment_time,money,interest_rate,loan_type,borrower,status')->find();//待还总金额
        if (empty($certificate)) {
            $data['ret'] = '1002';
            $data['code'] = '订单异常';
            $this->return = ['data' => $data];
            return true;
        }
//
//        $data['numbering']='P2018153291388691915924w';//订单号
//        //$data['initiate_id']='80';
//        $data['loan_time']=time();//借款时间
//        $data['repayment_time']=time();//还款时间
//        $data['money']=1000;//借款金额
//        $data['interest_rate']=10;//年利率
//        $data['loan_type']='日常消费';
//        $data['borrower']='借款人';
//        $data['status']=2;
        switch ($certificate["loan_type"]) {
            case 1:
                $certificate["loan_type"] = '日常消费';
                break;
            case 2:
                $certificate["loan_type"] = '医疗';
                break;
            case 3:
                $certificate["loan_type"] = '旅游';
                break;
            case 4:
                $certificate["loan_type"] = '装修';
                break;
            case 5:
                $certificate["loan_type"] = '教育';
                break;
            default:
                $certificate["loan_type"] = '日常消费';
                break;
        }
        $data7["user_id"] = "5";//发送人id
        $data7["user_name"] = "系统消息";//发送人姓名
        $data7["receive_id"] = $receive_id;//接收人id
        $data7["receive_name"] = $certificate['borrower'];//接收人姓名
        $data7["message"] = json_encode($certificate);//消息内容
        $data7["send_time"] = time();
        $data7["type"] = 4;//1语音消息2图片3语音,4凭证，5订单，
        $data7["voic_time"] = 0;//语音时长
        $data77 = json_encode($data7, JSON_UNESCAPED_UNICODE);

        if ($gateway->isUidOnline($receive_id) == 1) {
            $gateway->sendToUid($receive_id, $data77);
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $this->return = ['data' => $data];
            return true;
        } else {
            $chat_record_copy = M('chat_record_copy', Null, 'DB2')->add($data7);
            if ($chat_record_copy) {
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $this->return = ['data' => $data];
                return true;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '发送失败';
                $this->return = ['data' => $data];
                return false;
            }
        }
    }

    /*
     * 账单推送api
     */
    public function bill_push_api()
    {
        $receive_id = I('receive_id');
        if (empty($receive_id)) {
            $data['ret'] = '1002';
            $data['code'] = '接收人id为空';
            $this->return = ['data' => $data];
            return false;
        }
        $user = M('user', Null, 'DB2')->where(['id' => $receive_id, 'is_delete' => 1])->field("username")->find();//总数
        if (empty($user)) {
            $data['ret'] = '1002';
            $data['code'] = '用户不存在';
            $this->return = ['data' => $data];
            return false;
        }
        $gateway = new \Home\Service\Gateway();
        $status = ["in", '2,3,4,6,9'];
        $status1 = ["in", '2, 3, 4,9'];
        $certificate = M('certificate', Null, 'DB2')->where(["borrower_id" => 80, "status" => $status])->Sum("money");//总数
        $user_Sum = M('certificate', Null, 'DB2')->where(["borrower_id" => 80, "status" => $status1])->Sum("interest");//待还总金额

        $user_Min = M('certificate', Null, 'DB2')->where(["borrower_id" => 80, "status" => $status1])->Min("repayment_time");//总数
        $user_mob = M('certificate', Null, 'DB2')->where(["borrower_id" => 80, "status" => $status1, "repayment_time" => $user_Min])->order("repayment_time desc")->field("interest,repayment_time")->find();
        $user_mob["top_interest"] = empty($user_mob["interest"]) ? 0 : $user_mob["interest"];
        $user_mob["repayment_time"] = empty($user_mob["repayment_time"]) ? 0 : date('Y-m-d', $user_mob["repayment_time"]);//最新一期还款时间
        $user_mob["certificate"] = empty($user_Sum) ? 0 : $user_Sum;///待还款总金额
        $user_mob["user_Sum"] = empty($certificate) ? 0 : $certificate;///总借款金额


        $data7["user_id"] = "5";//发送人id
        $data7["user_name"] = "系统消息";//发送人姓名
        $data7["receive_id"] = $receive_id;//接收人id
        $data7["receive_name"] = '测试';//接收人姓名
        $data7["message"] = json_encode($user_mob);//消息内容
        $data7["send_time"] = time();
        $data7["type"] = 5;//1语音消息2图片3语音4凭证5账单
        $data7["voic_time"] = 0;//语音时长
        $data77 = json_encode($data7, JSON_UNESCAPED_UNICODE);
        //$watch= M('chat_record_copy', Null, 'DB2')->add($data7);
        //echo $data77;
        //$gateway->sendToUid(80,$data77);
        if ($gateway->isUidOnline($receive_id) == 1) {
            $gateway->sendToUid($receive_id, $data77);
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $this->return = ['data' => $data];
            return true;
        } else {
            $chat_record_copy = M('chat_record_copy', Null, 'DB2')->add($data7);
            if ($chat_record_copy) {
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $this->return = ['data' => $data];
                return true;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '发送失败';
                $this->return = ['data' => $data];
                return true;
            }
        }
    }

    /*
 * 内部调用凭证推送消息api
 */
    public function DME_certificate_api($receive_id, $numbering)
    {
//        $receive_id = I('receive_id');
//        $numbering = I('numbering');
        if (empty($receive_id)) {
            $data['ret'] = '1002';
            $data['code'] = '接收人id为空';
            $this->return = ['data' => $data];
            return false;
        }
        if (empty($numbering)) {
            $data['ret'] = '1002';
            $data['code'] = '订单号为空';
            $this->return = ['data' => $data];
            return false;
        }
        $gateway = new \Home\Service\Gateway();

        $certificate = M('certificate', Null, 'DB2')->where(['borrower_id' => $receive_id, 'numbering' => $numbering, 'is_delete' => 1])
            ->field('numbering,loan_time,repayment_time,money,interest_rate,loan_type,borrower,status')->find();//待还总金额
        if (empty($certificate)) {
            $data['ret'] = '1002';
            $data['code'] = '订单异常';
            $this->return = ['data' => $data];
            return true;
        }
//
//        $data['numbering']='P2018153291388691915924w';//订单号
//        //$data['initiate_id']='80';
//        $data['loan_time']=time();//借款时间
//        $data['repayment_time']=time();//还款时间
//        $data['money']=1000;//借款金额
//        $data['interest_rate']=10;//年利率
//        $data['loan_type']='日常消费';
//        $data['borrower']='借款人';
//        $data['status']=2;
        switch ($certificate["loan_type"]) {
            case 1:
                $certificate["loan_type"] = '日常消费';
                break;
            case 2:
                $certificate["loan_type"] = '医疗';
                break;
            case 3:
                $certificate["loan_type"] = '旅游';
                break;
            case 4:
                $certificate["loan_type"] = '装修';
                break;
            case 5:
                $certificate["loan_type"] = '教育';
                break;
            default:
                $certificate["loan_type"] = '日常消费';
                break;
        }
        $data7["user_id"] = "5";//发送人id
        $data7["user_name"] = "系统消息";//发送人姓名
        $data7["receive_id"] = $receive_id;//接收人id
        $data7["receive_name"] = $certificate['borrower'];//接收人姓名
        $data7["message"] = json_encode($certificate);//消息内容
        $data7["send_time"] = time();
        $data7["type"] = 4;//1语音消息2图片3语音,4凭证，5订单，
        $data7["voic_time"] = 0;//语音时长
        $data77 = json_encode($data7, JSON_UNESCAPED_UNICODE);

        if ($gateway->isUidOnline($receive_id) == 1) {
            $gateway->sendToUid($receive_id, $data77);
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $this->return = ['data' => $data];
            return true;
        } else {
            $chat_record_copy = M('chat_record_copy', Null, 'DB2')->add($data7);
            if ($chat_record_copy) {
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $this->return = ['data' => $data];
                return true;
            } else {
                $data['ret'] = '1002';
                $data['code'] = '发送失败';
                $this->return = ['data' => $data];
                return true;
            }
        }
    }

    /*
     * 客服发送提示语
     */
    public function Customer()
    {
        $gateway = new \Home\Service\Gateway();
        $get = I('data');
        $get = $this->jiemi($get);
        $user_id = $get["user_id"];///用户唯一标识
        $kefu = M('user', '', C('DB2'))->where(['id' => $user_id,'is_delete'=>1])->field('username,chat_id,channel,shop_identifier')->find();
//        if (!empty($kefu['channel']) && $kefu['chat_id'] == 0 || $kefu['chat_id'] == 1) {
//            $shopkeeper_kefu = M('shopkeeper', '', C('DB2'))->where(['shop_idenfier' => $kefu['shop_identifier'], 'state' => 1])->order(['ctime desc'])->field('id,account,rid')->select();
//            foreach ($shopkeeper_kefu as $key => $value) {
//                $domain = strstr($value['rid'], '4');
//                if($domain!==false){
//                    //$kefuid[$value['id']] = $value['id'];///在线客服id
//
//                    switch ($gateway->isUidOnline($value['account'])) {
//                        case 1:
//                            $kefuid[$value['id']] = $value['id'];///在线客服id
//                            break;
//                    }
//                }
//            }
//        }
        if ($kefu['chat_id'] == 0 || $kefu['chat_id'] == 1) {
            $shopkeeper_kefu = M('shopkeeper', '', C('DB2'))->where(['shop_idenfier' => $kefu['shop_identifier'], 'state' => 1])->order(['ctime desc'])->field('id,account,rid')->select();
            foreach ($shopkeeper_kefu as $key => $value) {
                $domain = strstr($value['rid'], '4');
                $v2_domain = strstr($value['rid'], '10');
                if($domain!==false||$v2_domain!==false) {
                    switch ($gateway->isUidOnline($value['account'])) {
                        case 1:
                            $kefuid[$value['id']] = $value['id'];///在线客服id
                            break;
                    }
                }
            }
                if (empty($kefuid)) {
                    return false;
                }
                $kefuid = array_rand($kefuid, 1);
                M('user', '', C('DB2'))->where(['id' => $user_id, 'is_delete' => '1'])->save(['chat_id' => $kefuid]);
                $kefudata = M('communication', '', C('DB2'))->where(['shop_id' => $kefuid])->field('account,nickname')->find();
                $data7["user_id"] = $kefudata['account'];//发送人id
                $data7["user_name"] = $kefudata['nickname'];//发送人姓名
                $data7["receive_id"] = $user_id;//接收人id
                $data7["receive_name"] = $kefu['username'];//接收人姓名
                $data7["message"] = '您的专属客服' . $kefudata['nickname'] . '已上线，有任何问题可以联系我哦';//消息内容
                $data7["send_time"] = time();
                $data7["type"] = 1;//1语音消息2图片3语音
                $data7["voic_time"] = 0;//语音时长
                $data77 = json_encode($data7, JSON_UNESCAPED_UNICODE);
                $gateway->sendToUid($user_id, $data77);
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return true;
            } else {
                $kefudata = M('communication', '', C('DB2'))->where(['shop_id' => $kefu['chat_id']])->field('account,nickname')->find();
                $data7["user_id"] = $kefudata['account'];//发送人id
                $data7["user_name"] = $kefudata['nickname'];//发送人姓名
                $data7["receive_id"] = $user_id;//接收人id
                $data7["receive_name"] = $kefu['username'];//接收人姓名
                $data7["message"] = '您的专属客服' . $kefudata['nickname'] . '已上线，有任何问题可以联系我哦';//消息内容
                $data7["send_time"] = time();
                $data7["type"] = 1;//1语音消息2图片3语音
                $data7["voic_time"] = 0;//语音时长
                $data77 = json_encode($data7, JSON_UNESCAPED_UNICODE);
                $gateway->sendToUid($user_id, $data77);
                $data['ret'] = '1001';
                $data['code'] = 'success';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                return true;
            }
            //$watch= M('chat_record_copy', Null, 'DB2')->add($data7);
            //echo $data77;

            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        }


    /*
     * 客服转移用户接口
     */
    public function chat_transfer_user()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $chat_id = $get["chat_id"];///客服id
        $uid = $get["uid"];//转移用户的id
        $list_id = $get["list_id"];//对方客服id
        if (empty($chat_id)) {
            $data['ret'] = '1002';
            $data['code'] = '请先登录';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($uid)) {
            $data['ret'] = '1002';
            $data['code'] = '用户异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if (empty($list_id)) {
            $data['ret'] = '1002';
            $data['code'] = '客服账号异常';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $chat_user = M('user', Null, 'DB2')->where(['id' => $uid, 'chat_id' => $chat_id])->field('id,shop_identifier')->find();//是否属于自己的用户
        if (empty($chat_user)) {
            $data['ret'] = '1002';
            $data['code'] = '该用户不属于你，不能转移，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $chat_shopkeeper = M('shopkeeper', Null, 'DB2')->where(['id' => $list_id, 'state' => 1])->field('id,account')->find();//转移的客服id
        if (empty($chat_shopkeeper['id'])) {
            $data['ret'] = '1002';
            $data['code'] = '该客服已被禁用或删除，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $time = time();
        //user_chat_now//
        $user = M('user', Null, 'DB2')->where(['id' => $uid, 'chat_id' => $chat_id])->save(['chat_id' => $chat_shopkeeper['id'], 'utime' => time()]);//是否属于自己的用户
        if ($user) {
            M('chat_now', Null, 'DB2')->add(['user_id' => $uid, 'chat_id' => $chat_shopkeeper['id'], 'ctime' => $time]);
            //if($chat_user['shop_identifier']=='0100010020') {
                $gateway = new \Home\Service\Gateway();
                $label = M('user', Null, 'DB2')
                    ->join("u left join label_id l_id on u.id=l_id.user_id")
                    ->join("left join label l on l.id=l_id.label_id")
                    ->join("left join user_chat_now uc on uc.chat_id=$chat_id")
                    ->join("left join user_identity uid on uid.user_id=u.id")
                    ->where(["l.is_dell" => 1, "u.id" => $uid, 'u.is_delete' => 1])
                    ->order("l.name desc")
                    ->limit(1)
                    ->field("l.id,l_id.user_id,l.name,u.username,uid.hold")
                    ->group("u.id")
                    //->fetchSql(true)
                    ->select();
                //$updata_user_list = json_encode($label);
                $data7['type'] = 'update_user_list';
                $data7['data'] = $label;
                $gateway->sendToUid($chat_shopkeeper['account'], json_encode($data7));//像对方发送消息
            //}
            $data['ret'] = '1001';
            $data['code'] = 'success';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            $data['ret'] = '1002';
            $data['code'] = '转移失败，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }

    /*
     * 商户客服列表  转移用户使用
     */
    public function dme_chat_list()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $chat_id = $get["chat_id"];///客服id
        $char_shopkeeper = M('shopkeeper', Null, 'DB2')->where(['id' => $chat_id])->field('id,rid')->find();//是否属于自己的用户
        $domain = strstr($char_shopkeeper['rid'], '4');//是否有客服角色权限
        $v2_domain = strstr($char_shopkeeper['rid'], '10');//是否有客服角色权限
        if (empty($domain)&&empty($v2_domain)) {
            $data['ret'] = '1002';
            $data['code'] = '该账号没有客服权限，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $shop_identifier = $get['shop_identifier'];//商户号
        $shopkeeper = M('communication', Null, 'DB2')->where(['shop_identifier' => $shop_identifier, 'commun_state' => 1])->field('shop_id as id,nickname as name')->select();//是否属于自己的用户
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($shopkeeper) ? 1 : 0;
        $data['data'] = $shopkeeper;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    /*
     * WEB信用卡渠道编码对照列表
     */
    public function channel_coding_list()
    {
        $channel_coding = M('channel_coding', Null, 'DB2')->where(['type' => '邮箱'])->field('id,logo,data_type,channel_code')->select();//是否属于自己的用户
        $data['ret'] = '1001';
        $data['code'] = 'success';
        $data['is_null'] = empty($channel_coding) ? 1 : 0;
        $data['data'] = $channel_coding;
        $data1 = $this->jiami($data);
        $this->return = ['data' => $data1];
        return true;
    }

    function post2($url, $data)
    {//file_get_content

        $postdata = http_build_query(
            $data
        );
        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    /*
     * 信用卡认证回调接口
     */
    public function credit_cardCallback()
    {
        $get = I('data');
        $get = $this->jiemi($get);
        $taskid = $get['task_id'];
        if (empty($taskid)) {
            $data['ret'] = '1002';
            $data['code'] = '数据异常，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }

        $date['task_id'] = $taskid;
        $url = "https://api.shujumohe.com/octopus/task.unify.query/v3?partner_code=sharedcash&partner_key=dfc99c9bad014db59fc7ed6d4187ae49";

        //$header=array('method'  => 'POST','Content-type: application/x-www-form-urlencoded','charset:utf-8');

        //$header = array('Content-Type:application/x-www-form-urlencoded;charset=utf-8');
        //$res=$this->set_curl($url,$date,$header);
        for ($i = 0; $i < 9; $i++) {
            $res = $this->post2($url, $date);
            $res = json_decode($res, true);
//            $data['installment_info'] = $res;
//            $channel_coding = M('credit_card_callback', '', 'DB2')->add($data);
//            return true;
            if ($res['code'] == '1' || $res['code'] == '200' || $res['code'] == '1057' || $res['code'] == '1070' || $res['code'] == '2006' || $res['code'] == '2019' || $res['code'] == '2414' || $res['code'] == '132') {
                //M('user', '', C('DB2'))->where(array('id' => $v['id'], 'is_delete' => '1'))->setField('alipay_verify', '4');
                //M('mh_alipay_account_info', '', C('DB2_ZX'))->where(array('user_id' => $v['id'], 'status' => '1', 'task_id' => $zfb_report))->setField('status', '2');
                continue;
            }
            if ($res['code'] == '100' || $res['code'] == '2012') {
                continue;
            }
            if ($res['code'] == 0 || $res['code'] == 2011) {
                $res = $res['data'];
                $add_data['channel_type'] = $res['channel_type'];//渠道类型。见渠道编码对照表
                $add_data['channel_code'] = $res['channel_code'];//渠道编码。见渠道编码对照表
                $add_data['channel_src'] = $res['channel_src'];//渠道数据源
                $add_data['channel_attr'] = $res['channel_attr'];//渠道属性
                $add_data['real_name'] = $res['real_name'];//真实姓名
                $add_data['identity_code'] = $res['identity_code'];//身份证号码
                $add_data['user_mobile'] = $res['user_mobile'];//手机号码
                $add_data['created_time'] = $res['created_time'];//任务创建时间
                $add_data['user_name'] = $res['user_name'];//用户名

                $task_data = json_decode($res['task_data'], true);//原始数据
                $task_data = $task_data['billing_check_list'];//billing_check_list数组
                $add_data['bank'] = $task_data['bank'];//银行名称
                $add_data['bank_type'] = $task_data['bank_type'];//银行缩写
                $add_data['bank_card_type'] = $task_data['bank_card_type'];//银行卡管理类型
                $sheets = $task_data['sheets'];//sheets数组
                $add_data['billing_info'] = json_encode($sheets['billing_info']);//账单信息
                $add_data['payment_info'] = json_encode($sheets['payment_info']);//账单明细
                $add_data['trans_info'] = json_encode($sheets['trans_info']);//账单流水
                $add_data['installment_info'] = json_encode($sheets['installment_info']);//分期明细
                M('credit_card_callback', '', 'DB2')->startTrans();
                M('user', '', 'DB2')->startTrans();
                $channel_coding = M('credit_card_callback', '', 'DB2')->add($add_data);
                $user = M('user', '', 'DB2')->where(['mobile' => $res['user_mobile'], 'identity_num' => $res['identity_code'], 'is_delete' => 1])->save(['credit_verify' => 3]);
                break;
            }
        }
        if ($channel_coding && $user) {
            M('credit_card_callback', '', 'DB2')->commit();
            M('user', '', 'DB2')->commit();
            $data['ret'] = '1001';
            $data['code'] = 'success，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        } else {
            M('credit_card_callback', '', 'DB2')->rollback();
            M('user', '', 'DB2')->rollback();
            $data['ret'] = '1002';
            $data['code'] = '绑定失败';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }

    }
    /*
     * 商户logo
     */
    public function merchant_logo(){
        $get = I('data');
        $get = $this->jiemi($get);
        $shop_identifier=$get['shop_identifier'];//商户号
        if(empty($shop_identifier)){
            $data['ret'] = '1002';
            $data['code'] = '商户号为空!';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        //$shop_identifier='0100010020';
        $merchant=M('merchant','','DB2')->where(['shop_identifier'=>$shop_identifier,'status'=>1])->field('merchant_name,logo,ios_url,app_url')->find();
        $merchant['ios_url']=empty($merchant['ios_url'])?'':$merchant['ios_url'];
        $merchant['app_url']=empty($merchant['app_url'])?'':$merchant['app_url'];
        if($merchant){
            $data['ret'] = '1001';
            $data['code'] = 'success，';
            $data['data']=$merchant;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return true;
        }else{
            $data['ret'] = '1002';
            $data['code'] = '获取失败';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }
    /*
*测试消息
*/
    public function ceshixaoxi()
    {
        $gateway = new \Home\Service\Gateway();
        $data["user_id"] = "31";//发送人id
        $data["user_name"] = "彭政";///发送人姓名
        $data["receive_id"] = "xia";//接收人id
        $data["receive_name"] = "xia";///接收人姓名
        $data["message"] = "测试消息asdasda";//消息内容
        $data["type"] = 1;//消息类型，1文字表情，2图片，3语音，4凭证
        $data["send_time"] = time();//发送时间
        $data["voic_time"] = 0;//语音消息
        $data4 = json_encode($data, JSON_UNESCAPED_UNICODE);
        $gateway->sendToUid('xia', $data4);//像对方发送消息
    }

    public function redis()
    {
        $redis = new \Redis();
        $redis->connect('xycshop0577.redis.rds.aliyuncs.com');  //地址与端口
        $redis->auth('Dstl0577');  ///密码
//        $redis ->rpush( "cecece" , "123");
//        $redis ->rpush( "cecece" , "456");
//        $redis ->rpush( "cecece" , "789");
//        $redis ->rpush( "cecece" , "369");
        $user_id=1;
        $chat='严浩';
        //$chat[$user_id];
        var_dump($chat[$user_id]);die;
//        if ($redis->get($chat[$user_id])) {
//            echo $redis->get($chat[$user_id]);
//            return true;
//        } else {
//            $redis ->set( $chat[$user_id] , "123456789",50);
//            echo $redis->get($chat[$user_id]);
//
//            return true;
//        }
    }

    /*
      * 测试语音验证码
      * $mobile 手机号
      */
    public function voice_code($mobile){
        //$mobile='13003940779';

       $code=(string)rand(1000,9999);
        $mobilecode="   $code[0]    $code[1]    $code[2]    $code[3]";
        S($mobile.'phonechang_verify',$code);
        S($mobile.'phonechang_time',time());
        $url="http://xycshop.dstlkj.com/ChatApi/voice_code?phone=$mobile&code=".$mobilecode;
        $header = array('Content-Type:application/json;charset=utf-8');
        $result = self::get_curl($url,'',$header);
        //return json_decode($result,true);
        $result=json_decode($result,true);
        if($result['code']=='1001'){
            $data['ret']='1001';
            $data['code']='语音验证码已成功发送,请注意接听';
            echo json_encode($data);
            exit;
        }else{
            $data['ret']='1002';
            $data['code']='发送失败,请联系管理员';
            echo json_encode($data);
            exit;
        }
    }
    public function get_curl($url = '',$data='',$header='')
    {

        $ch = curl_init();
        if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, '1');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        if (curl_error($ch)) {
            return '错误信息:' . curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }
}